<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="1000" :close-on-click-modal="false" :show-close="true">
            <el-form :model="formData" ref="formRef" :rules="rules" >
                <div class="form-section">
     
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="入库日期">
                                <el-date-picker v-model="formData.date" type="date" placeholder="请选择" style="width: 100%;" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备注">
                                <el-input v-model="formData.remark" placeholder="请输入" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </div>

                <div class="product-section">
                    <div class="product-header">
                        <span class="product-title">入库产品</span>
                    </div>
                    <el-table :data="formData.products" border style="width: 100%; margin-top: 10px;">
                        <el-table-column prop="name" label="产品名称" />
                        <el-table-column prop="spec" label="规格型号" />
                        <el-table-column prop="unit" label="单位" width="80" />
                        <el-table-column prop="warehouse" label="出库仓库" width="120">
                            <template #default="{ row }">
                                <el-input readonly @click="showWarehouseDialog = true" v-model="row.warehouse" size="small" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="danumber" label="库存数量"  />
                        <el-table-column prop="quantity" label="本次出库数量"  >
                            <template #default="{ row }">
                                <el-input v-model="row.quantity" size="small" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" width="120">
                        </el-table-column>
                        <el-table-column label="操作" width="80">
                            <template #default="{ $index }">
                                <el-button type="text" style="color: #F56C6C;" @click="confirmRemove($index)">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="submitForm">
                        确定
                    </el-button>
                </div>
            </template>

            <!-- 二次确认弹窗 -->
            <el-dialog
                v-model="removeDialogVisible"
                title="提示"
                width="300px"
                :show-close="false"
                append-to-body
            >
                <div style="text-align:center;">确定要移除该产品吗？</div>
                <template #footer>
                    <el-button @click="removeDialogVisible = false">取消</el-button>
                    <el-button type="danger" @click="removeProduct">确定</el-button>
                </template>
            </el-dialog>
        </el-dialog>
        <StorageWarehouseDialog
            v-model:dialogVisible="showWarehouseDialog"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import api from "@/api";
import StorageWarehouseDialog from './StorageWarehouseDialog.vue';

// 接收父组件传入的值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogType: {
        type: String,
        default: 'add'
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});




const emit = defineEmits(['update:dialogVisible', 'submit']);

// 表单ref
const formRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入仓库编号', trigger: 'blur' }],
    type: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
});


// 弹窗标题
const dialogTitle = computed(() => {
    const titleMap = {
        add: '其他出库',
        edit: '其他出库',
        addSub: '新增子仓库',
        editSub: '编辑子仓库'
    };
    return titleMap[props.dialogType] || '仓库信息';
});

// 表单数据
const formData = reactive({
    id: '',
    name: '',
    code: '',
    type: '',
    phone: '',
    address: '',
    remark: '',
    manager: '',
    parent_id: '',
    parent_name: '',
    warehouse: '',
    warehouseCode: '',
    date: '',
    products: [{}]
});

// 监听对话框显示状态
const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => {
        emit('update:dialogVisible', val);
    }
});

// 监听props变化
watch(() => props.dialogVisible, (newVal) => {
    if (newVal) {
        // 打开弹窗时，初始化表单数据
        initFormData();
    }
});

let showProductDialog = ref(false);
// 初始化表单数据
const initFormData = () => {
    // 清空表单
    Object.keys(formData).forEach(key => {
        if (key !== 'products') {
            formData[key] = '';
        }
    });

    // 如果是编辑模式，填充表单数据
    if (props.dialogType === 'edit' || props.dialogType === 'editSub') {
        Object.keys(props.dialogRow).forEach(key => {
            if (key in formData) {
                formData[key] = props.dialogRow[key];
            }
        });

        // 特殊处理一些字段
        if (props.dialogRow.title) {
            formData.name = props.dialogRow.title;
        }
        if (props.dialogRow.house_type) {
            formData.type = props.dialogRow.house_type;
        }
        formData.id = props.dialogRow.id || '';
    }

    // 如果是添加子仓库，设置父仓库信息
    if (props.dialogType === 'addSub') {
        formData.parent_id = props.dialogRow.parent_id || '';
        formData.parent_name = props.dialogRow.parent_name || '';
    }
};

// 仓库选择自动带出编码
watch(() => formData.warehouse, (val) => {
    if (val === 'A') formData.warehouseCode = 'CKA001';
    else if (val === 'B') formData.warehouseCode = 'CKB002';
    else formData.warehouseCode = '';
});

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();

        // 构建提交数据
        const submitData = {
            title: formData.name,
            code: formData.code,
            house_type: formData.type,
            manager: formData.manager,
            phone: formData.phone,
            address: formData.address,
            remark: formData.remark,
            date: formData.date,
            products: formData.products
        };

        // 添加或编辑主仓库
        if (props.dialogType === 'add') {
            const res = await api.parking.add(submitData);
            if (res.code === 0) {
                ElMessage.success('添加成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '添加失败');
            }
        }
        // 编辑主仓库
        else if (props.dialogType === 'edit') {
            const res = await api.parking.update({
                ...submitData,
                id: formData.id
            });
            if (res.code === 0) {
                ElMessage.success('更新成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '更新失败');
            }
        }
        // 添加子仓库
        else if (props.dialogType === 'addSub') {
            const res = await api.parking.addSub({
                ...submitData,
                parent_id: formData.parent_id
            });
            if (res.code === 0) {
                ElMessage.success('添加子仓库成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '添加子仓库失败');
            }
        }
        // 编辑子仓库
        else if (props.dialogType === 'editSub') {
            const res = await api.parking.updateSub({
                ...submitData,
                id: formData.id,
                parent_id: formData.parent_id
            });
            if (res.code === 0) {
                ElMessage.success('更新子仓库成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '更新子仓库失败');
            }
        }
    } catch (error) {
        console.error('表单提交错误', error);
        ElMessage.error('请检查表单填写是否正确');
    }
};


const removeDialogVisible = ref(false);
const removeIndex = ref(null);



// 二次确认逻辑
function confirmRemove(index) {
    removeIndex.value = index;
    removeDialogVisible.value = true;
}

function removeProduct() {
    if (removeIndex.value !== null) {
        formData.products.splice(removeIndex.value, 1);
        removeIndex.value = null;
        removeDialogVisible.value = false;
    }
}



const selectedProducts = ref([]);


let showWarehouseDialog = ref(false);

</script>

<style lang="scss" scoped>


::v-deep .form-section{
    padding-top: 0px !important;
}

::v-deep .el-form-item__label{
    margin-left: 6px !important;
}

::v-deep .el-form-item__label-wrap{
    margin-left: 0px !important;
}

::v-deep .el-form-item{
    display: block;
}


:deep(.el-dialog) {
    --el-dialog-padding-primary: 0px;
}

:deep(.el-dialog__header) {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

:deep(.dialog-footer) {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #000;
}

:deep(.el-dialog__body) {
    padding: 20px 10px;
    padding-right: 30px;
}

.form-section {

    padding: 20px 20px 0 20px;
    border-radius: 4px 4px 0 0;
}

.product-section {
    background: #fff;
    padding: 20px;
    padding-bottom: 0px;
    border-radius: 0 0 4px 4px;
}

.product-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;
}

.product-title {
    font-weight: bold;
    font-size: 16px;
    border-left: 3px solid #3a5fff;
    padding-left: 8px;
}
</style>
